package com.cqc.jdk8.Jlang.thread;

import org.junit.Test;

import java.text.DateFormat;
import java.util.Date;
import java.util.concurrent.*;

/**
 * @author cui
 * @date 2025/6/15 17:35
 * @description Thread实例的几个方法
 **/
public class Thread2Test {

    @Test
    public void start() {
        AThread thread = new AThread();
//        thread.start();//Thread-0....AThread.run()
        thread.run();//main....AThread.run()  run方法不会创建线程
    }

    @Test
    public void setName() {
        AThread thread = new AThread();
        thread.setName("我是AThread");
        thread.start();//我是AThread....AThread.run()
    }


    @Test
    public void getName() throws Exception {
        ExecutorService executorService2 = Executors.newFixedThreadPool(3);
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                //pool-2-thread-1....ExecutorService.call()  项目有2个线程池时
                //pool-1-thread-1....ExecutorService.call()  项目只有1个线程池时
                System.out.println(Thread.currentThread().getName() + "....ExecutorService.call()");
            }
        });
        executorService.shutdown();
    }

    @Test
    public void setPriority() {
        for (int i = 0; i < 50; i++) {
            AThread aThread = new AThread();
            aThread.setPriority(Thread.MAX_PRIORITY);
            aThread.start();

            BThread bThread = new BThread();
            bThread.setPriority(Thread.MIN_PRIORITY);
            bThread.start();
        }
    }

    @Test
    public void setDaemon() {
        CThread cThread = new CThread();
        cThread.setDaemon(true);
        cThread.start();
    }

    /**
     * thread.join()在方法A中，那么阻塞的即使A所在的线程
     */
    @Test
    public void join() throws InterruptedException {
        System.out.println("main开始，" + DateFormat.getDateTimeInstance().format(new Date()));
        CThread cThread = new CThread();
        cThread.start();

        cThread.join();
        System.out.println("main结束，" + DateFormat.getDateTimeInstance().format(new Date()));
    }

    @Test
    public void interrupt() throws InterruptedException {
        DThread dThread = new DThread();
        dThread.start();

        TimeUnit.SECONDS.sleep(10);
        // 检查线程是否中断，没有尝试终止线程
        if (!dThread.isInterrupted()) {
            dThread.interrupt();
        }
    }

    @Test
    public void threadStaticMethod() {
        EThread eThread = new EThread();
        eThread.start();
    }

    /**
     * Thread.yield();当暂停当前线程A，先走其它线程BCD，其它的走完了，再走A
     */
    @Test
    public void yield() {
        FThread fThread = new FThread("f");
        GThread gThread = new GThread("g");
        fThread.start();
        gThread.start();
    }

    /**
     * holdsLock()  方法加锁了，返回true;方法外没有锁，结果是false
     */
    @Test
    public void holdsLock() {
        HThread hThread = new HThread();
        hThread.start();
    }
}
